package com.english.controller;

import com.english.entity.Banner;
import com.english.entity.User;
import com.english.service.BannerService;
import com.english.service.UserService;
import com.english.utils.R;
import com.english.vo.HomeDataVO;
import com.english.vo.UserInfoVO;
import com.english.vo.QuickActionVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 首页控制器
 * 将登录后的用户信息同步到首页显示
 * 
 * @author wlq
 * @since 2025-08-05
 */
@RestController
@RequestMapping("/api/home")
@CrossOrigin(origins = "*", allowCredentials = "false", maxAge = 3600)
public class HomeController {

    @Autowired
    private UserService userService;
    
    @Autowired
    private BannerService bannerService;

    /**
     * 获取首页数据（同步登录信息）
     * 包含用户信息、统计数据、轮播图等
     * 
     * @param authorization 用户认证token（请求头）
     * @param token 用户认证token（请求参数）
     * @return 首页数据
     */
    @GetMapping("/data")
    public R<HomeDataVO> getHomeData(
            @RequestHeader(value = "Authorization", required = false) String authorization,
            @RequestParam(value = "token", required = false) String token) {
        try {
            // 1. 从token获取用户信息（优先使用请求头，其次使用请求参数）
            String authToken = authorization != null ? authorization : token;
            if (authToken == null) {
                return R.error("缺少认证token");
            }
            
            String wechatId = extractWechatIdFromToken(authToken);
            if (wechatId == null) {
                return R.error("无效的token");
            }
            
            User user = userService.getUserByWechatId(wechatId);
            if (user == null) {
                return R.error("用户不存在");
            }
            
            // 2. 获取用户统计数据
            Map<String, Object> stats = userService.getUserStats(user.getId());
            
            // 3. 获取轮播图
            List<Banner> banners = bannerService.getActiveBanners();
            
            // 4. 组装首页数据
            HomeDataVO homeData = new HomeDataVO();
            homeData.setUserInfo(buildUserInfo(user));
            homeData.setStats(stats);
            homeData.setBanners(banners);
            homeData.setQuickActions(buildQuickActions());
            
            return R.success("获取首页数据成功", homeData);
            
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("获取首页数据失败：" + e.getMessage());
        }
    }

    /**
     * 从token中提取wechatId
     * 
     * @param token 认证token
     * @return wechatId
     */
    private String extractWechatIdFromToken(String token) {
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
        }
        
        if (token != null && token.startsWith("token_")) {
            String[] parts = token.split("_");
            if (parts.length >= 2) {
                return parts[1];
            }
        }
        
        return null;
    }

    /**
     * 构建用户信息
     * 
     * @param user 用户实体
     * @return 用户信息Map
     */
    private Map<String, Object> buildUserInfo(User user) {
        Map<String, Object> userInfo = new HashMap<>();
        userInfo.put("id", user.getId());
        userInfo.put("name", user.getName());
        userInfo.put("role", user.getRole());
        userInfo.put("roleText", user.getRole() == 0 ? "学生" : "管理员");
        userInfo.put("phone", user.getPhone());
        return userInfo;
    }

    /**
     * 构建快速功能入口列表
     * 
     * @return 功能入口列表
     */
    private List<Map<String, Object>> buildQuickActions() {
        List<Map<String, Object>> actions = new ArrayList<>();
        
        // 预约小课
        Map<String, Object> booking = new HashMap<>();
        booking.put("id", "booking");
        booking.put("name", "预约小课");
        booking.put("icon", "calendar");
        booking.put("color", "#007AFF");
        booking.put("url", "/pages/booking/index");
        actions.add(booking);
        
        // 课程安排
        Map<String, Object> schedule = new HashMap<>();
        schedule.put("id", "schedule");
        schedule.put("name", "课程安排");
        schedule.put("icon", "chart");
        schedule.put("color", "#34C759");
        schedule.put("url", "/pages/schedule/index");
        actions.add(schedule);
        
        // 课时管理
        Map<String, Object> management = new HashMap<>();
        management.put("id", "management");
        management.put("name", "课时管理");
        management.put("icon", "clock");
        management.put("color", "#FF9500");
        management.put("url", "/pages/management/index");
        actions.add(management);
        
        
        return actions;
    }
}